import {createRouter, createWebHistory} from 'vue-router'
import {constantRouter} from '@/router/routes'
import {close, start} from '@/utils/nprogress';
import {manageRouter} from "@/router/manageRouter.ts";
import {userRouter} from "@/router/userRouter.ts";

const router = createRouter({
    history: createWebHistory(),
    routes: constantRouter,
    scrollBehavior() {
        return {
            left: 0,
            top: 0,
        }
    },
})
// 路由前置后卫
router.beforeEach((to, from, next) => {
    // 开启进度条
    start();

    // 展平 manageRouter 的子路由
    const allManageRoutes = manageRouter.flatMap(route => {
        if (route?.children) {
            return route?.children.map(child => ({...child, parent: route}));
        }
        return route;
    });
    // 如果是公共页面，直接放行
    if (userRouter.some(route => route.path === to.path)) {
        next();
    } else if (to.path === '/login') {
        next();
    } else if (allManageRoutes.some(route => route.path === to.path)) {
        // 判断用户是否已登录
        const isLoggedIn = checkLoginStatus();
        // 如果是管理页面且未登录，重定向到登录页面
        if (!isLoggedIn) {
            next({path: '/login'});
        } else {
            next();
        }
    } else {
        // 其他情况，默认放行
        next();
    }
});
// 路由后置后卫
router.afterEach(() => {
    // 关闭进度条
    close();
});

// 检查登录状态
function checkLoginStatus() {
    // 从本地存储中获取 Token
    const token = localStorage.getItem("smart_admin_user_token");
    // 如果 Token 不存在，返回 false
    if (!token) {
        return false;
    } else {
        return true
    }
}

export default router
